//
//  KSOSContactListController.m
//  Keping
//
//  Created by a on 2017/9/19.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KSOSContactListController.h"
#import "KSOSAddContactController.h"
#import "KSOSContactListCell.h"
#import "KSOSRequest.h"
#import "KSosListModel.h"

@interface KSOSContactListController ()<UITableViewDelegate,UITableViewDataSource>
/**
 tableview
 */
@property(nonatomic,weak)UITableView*tableView;
/**
 footview
 */
@property(nonatomic,weak)UIView*footerView;
/**
 addbtn
 */
@property(nonatomic,weak)UIButton*addContactBtn;

/**
 数据源
 */
@property(nonatomic,strong)NSMutableArray*dataAry;

@end

@implementation KSOSContactListController
-(NSMutableArray *)dataAry
{
    if (!_dataAry) {
        _dataAry=[NSMutableArray array];
    }
    return _dataAry;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self loadData];
}

-(void)setUI
{
    self.navigationItem.title=@"SOS";
    
    UITableView*tableView=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.delegate=self;
    tableView.dataSource=self;
    [self.view addSubview:tableView];
    self.tableView=tableView;
    
    //添加table尾部
    UIView*footerView=[[UIView alloc]init];
    tableView.tableFooterView=footerView;
    footerView.backgroundColor=[UIColor clearColor];
    tableView.tableFooterView=footerView;
    self.footerView=footerView;
    
    UIButton*addContactBtn=[[UIButton alloc]initWithFrame:CGRectZero];
    [footerView addSubview:addContactBtn];
    self.addContactBtn=addContactBtn;
    addContactBtn.layer.masksToBounds=YES;
    addContactBtn.layer.borderWidth=1;
    addContactBtn.layer.borderColor=[UIColor colorWithHexString:@"#7f4afc"].CGColor;
    [addContactBtn setBackgroundColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addContactBtn setTitleColor:[UIColor colorWithHexString:@"#4f5ef9"] forState:UIControlStateNormal];
    [addContactBtn setTitle:@"Add New Contact" forState:UIControlStateNormal];
    addContactBtn.titleLabel.font=[UIFont boldSystemFontOfSize:20];
    [addContactBtn addTarget:self action:@selector(clickAddContact) forControlEvents:UIControlEventTouchUpInside];
    
}
-(void)clickAddContact
{
    KSOSAddContactController*vc=[KSOSAddContactController new];
    vc.vcType = KSOSAddContactVcTypeSOSContact;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.tableView.frame=self.view.bounds;
    
    self.footerView.frame=CGRectMake(0, 0, App_Frame_Width, K_FactorH(80));
    
    CGFloat margin =K_FactorW(20);
    CGFloat btnH=K_FactorH(50);
    self.addContactBtn.frame=CGRectMake(margin,self.footerView.height-btnH-margin,self.footerView.width-2*margin,btnH);
    self.addContactBtn.layer.cornerRadius=self.addContactBtn.height/2;
    
    self.tableView.tableFooterView=self.footerView;
}
#pragma mark -- UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataAry.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KSOSContactListCell*cell=[KSOSContactListCell cellWithTableView:tableView];
    cell.listModel = self.dataAry[indexPath.row];
    
    WEAKSELF
    cell.callback = ^(KSosListModel *listModel) {
      
        //删除
        [weakSelf showLoading];
        NSString *urlPath = [kSosListDeleteURL stringByReplacingOccurrencesOfString:@"{sosId}" withString:listModel.Id];
        KSOSRequest *deleteRequest = [[KSOSRequest alloc] initWithURL:urlPath];
        [deleteRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            [self hideHUD];
            NSDictionary *response = request.responseJSONObject;
            if ([response[@"statusCode"] integerValue] != 200) {
                
                [weakSelf showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
                return;
            }
            
            
            dispatch_async(dispatch_get_main_queue(), ^{                
                [weakSelf.dataAry removeObject:listModel];
                [weakSelf.tableView reloadData];
            });
            
            
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf hideHUD];
            [weakSelf showError:request.error];
        }];
        
    };
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return K_FactorH(75);
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return self.dataAry.count?K_FactorH(95/2):0.0f;
    
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.dataAry.count) {
        UIView*headerView=[[UIView alloc]init];
        headerView.backgroundColor=[UIColor colorWithHexString:@"#f2f1f6"];
        UILabel*titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(K_FactorW(10), 0, App_Frame_Width-2*K_FactorW(10), K_FactorH(95/2))];
        titleLabel.text=[NSString stringWithFormat:@"Emergency Contacts (%zd / 5 )",self.dataAry.count];
        [headerView addSubview:titleLabel];
        return headerView;
    }else
    {
        return nil;
    }
   
}

#pragma mark - 数据请求
- (void)loadData
{
    [self showLoading];
    KSOSRequest* loginRequest = [[KSOSRequest alloc] initWithURL:kSosListURL];
    [loginRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [self hideHUD];
        
        NSDictionary *response = request.responseJSONObject;
        if ([response[@"statusCode"] integerValue] != 200) {
            
            [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
            return;
        }
        
        
        NSMutableArray *arrayM = [NSMutableArray array];
        for (NSDictionary *dict in response[@"relationFriendViews"]) {
            KSosListModel *model = [KSosListModel modelWithDictionary:dict];
            [arrayM addObject:model];
        }
        
        self.dataAry = [NSMutableArray arrayWithArray:arrayM];
        [self.tableView reloadData];
        
        
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [self hideHUD];
        [self showError:request.error];
    }];
}


- (void)loadContactList:(void(^)(BOOL success, NSArray *contacts))completion
{
    KSOSRequest* loginRequest = [[KSOSRequest alloc] initWithURL:kSosListURL];
    [loginRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        
        NSDictionary *response = request.responseJSONObject;
        if ([response[@"statusCode"] integerValue] != 200) {
            
            [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
            return;
        }
        
        
        NSMutableArray *arrayM = [NSMutableArray array];
        for (NSDictionary *dict in response[@"relationFriendViews"]) {
            KSosListModel *model = [KSosListModel modelWithDictionary:dict];
            [arrayM addObject:model];
        }
        
        if (completion) {
            completion(YES, arrayM);
        }
        
        
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        
        if (completion) {
            completion(NO, nil);
        }
        
    }];
}


@end
